import { Container, TextInput, Textarea, Button, ScrollArea, Paper, Text, AppShell, NavLink, Group, Stack, Table, Modal, Avatar } from '@mantine/core';
import { useForm } from '@mantine/form';
import { IconSend } from '@tabler/icons-react';
import { useState, useEffect, useRef, KeyboardEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { HomePage, PCChatTable } from '../Home/Home.page';
import axios from 'axios';
import { LoginPage } from '../Login/Login.page';
import { PhoneChatTable, PhonePage } from '../Phone/Phone.page';
import { CameraChatTable, CameraPage } from '../Camera/Camera.page';
import { EarphoneChatTable, EarphonePage } from '../Earphone/Earphone.page';

interface SelectedItem {
    [key: string]: string | number | boolean | null;
}

export function ChatPage() {
    const navigate = useNavigate();
    const [active, setActive] = useState('chat');
    const [modalOpened, setModalOpened] = useState(false);
    const [selectedItem, setSelectedItem] = useState<SelectedItem | null>(null);
    const [messages, setMessages] = useState<{
        id: number;
        type: 'text' | 'image';
        content: string;
        isMe: boolean,
        messageType?: string
    }[]>([]);
    const form = useForm({
        initialValues: {
            message: '',
        },
    });

    const scrollRef = useRef<HTMLDivElement>(null);

    const handleSubmit = (values: { message: string }) => {
        if (values.message.trim()) {
            setMessages((current) => [
                ...current,
                {
                    id: Date.now(),
                    type: 'text',
                    content: values.message,
                    isMe: true
                },
            ]);
            form.reset();
        }
    };

    const handleViewDetails = async (id: string, type: string) => {
        try {
            const response = await axios.get(`/qa-api/${type}-detail/${id}`);
            if (response.data.success) {
                setSelectedItem(response.data.data);
                setModalOpened(true);
            }
        } catch (error) {
            console.error('获取详情失败:', error);
        }
    };

    useEffect(() => {
        if (messages.length > 0 && messages[messages.length - 1].isMe) {
            const timer = setTimeout(async () => {
                try {
                    const response = await axios.post('/qa-api/query', {
                        query: messages[messages.length - 1].content
                    });

                    if (response.data.success && response.data.data.results) {
                        let content = '';
                        if (response.data.data.query_type === 'pc') {
                            content = response.data.data.results.map((pc: any) => {
                                return `${pc.pc_name}\n品牌: ${pc.pc_brand}\n价格: ¥${pc.pc_price}\n配置信息:\n- CPU: ${pc.cpu_xinghao}\n- 内存: ${pc.neicun_rongliang}GB ${pc.neicun_leixing}\n- 硬盘: ${pc.yingpan_rongliang}GB ${pc.yingpan_miaoshu}\n- 显卡: ${pc.graph_device}\n- 屏幕: ${pc.screen_size}英寸 ${pc.screen_resolution}\n推荐理由: ${pc.recommendation_reason}\n\n`;
                            }).join('-------------------\n');
                        } else if (response.data.data.query_type === 'phone') {
                            content = response.data.data.results.map((phone: any) => {
                                return `${phone.phone_name}\n品牌: ${phone.phone_brand}\n价格: ¥${phone.phone_price}\n基本信息:\n- 发布日期: ${phone.release_date}\n- 颜色: ${phone.colors}\n- 尺寸: ${phone.length}x${phone.width}x${phone.thickness}mm\n屏幕参数:\n- 尺寸: ${phone.screen_size}英寸\n- 分辨率: ${phone.screen_resolution}\n- 刷新率: ${phone.refresh_rate}\n相机参数:\n- 前置: ${phone.front_cam_pixels}\n- 后置: ${phone.rear_cam_pixels}\n配置信息:\n- 内存: ${phone.ram_size}GB ${phone.ram_type}\n- 存储: ${phone.rom_size}GB ${phone.rom_type}\n- 电池: ${phone.battery_type}\n- 快充: ${phone.fast_charge}\n推荐理由: ${phone.recommendation_reason}\n\n`;
                            }).join('-------------------\n');
                        }

                        setMessages((current) => [
                            ...current,
                            {
                                id: Date.now(),
                                type: 'text',
                                content: content,
                                isMe: false,
                                list: response.data.data.results,
                                query_type: response.data.data.query_type
                            },
                        ]);
                    }
                } catch (error) {
                    setMessages((current) => [
                        ...current,
                        {
                            id: Date.now(),
                            type: 'text',
                            content: '抱歉，我遇到了一些问题，请稍后再试。',
                            isMe: false
                        },
                    ]);
                }
            }, 1000);
            return () => clearTimeout(timer);
        }
    }, [messages]);

    useEffect(() => {
        if (scrollRef.current) {
            scrollRef.current.scrollIntoView({ behavior: 'smooth' });
        }
    }, [messages]);

    const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
        if (event.key === 'Enter' && !event.shiftKey) {
            event.preventDefault(); // Prevents adding a new line
            form.onSubmit(handleSubmit)(); // Triggers form submission
        }
    };

    const renderContent = () => {
        switch (active) {
            case 'home':
                return <HomePage />;
            case 'chat':
                return (
                    <Stack justify="center" style={{ height: '100%' }}>
                        <Paper withBorder p="md" style={{
                            height: '70vh',
                            width: '100%',
                            backgroundColor: '#fff',
                            borderRadius: '12px',
                            boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)'
                        }}>
                            <ScrollArea style={{ height: '100%' }} offsetScrollbars>
                                {messages.map((message: any) => (
                                    <Paper
                                        key={message.id}
                                        p="xs"
                                        mb="xs"
                                        style={{
                                            marginLeft: message.isMe ? 'auto' : 0,
                                            backgroundColor: message.isMe ? '#007bff' : '#d0e7ff',
                                            color: message.isMe ? 'white' : 'black',
                                            width: 'fit-content',
                                            minWidth: '120px',
                                            maxWidth: '80%',
                                            whiteSpace: 'pre-wrap',
                                            wordBreak: 'break-word',
                                            borderRadius: message.isMe ? '18px 18px 4px 18px' : '18px 18px 18px 4px',
                                            padding: '8px 12px',
                                            boxShadow: '0 1px 3px rgba(0, 0, 0, 0.1)',
                                            animation: 'fadeIn 0.3s ease-in-out'
                                        }}
                                    >
                                        {message.type === 'text' ? (
                                            message.query_type ? (
                                                <Table withTableBorder withColumnBorders>
                                                    {message.query_type === 'camera' && (
                                                        <>
                                                            <CameraChatTable cameras={message.list}></CameraChatTable>
                                                        </>
                                                    )}
                                                    {message.query_type === 'earphone' && (
                                                        <>
                                                            <EarphoneChatTable earphones={message.list}></EarphoneChatTable>
                                                        </>
                                                    )}
                                                    {message.query_type === 'pc' && (
                                                        <>
                                                            <PCChatTable pcs={message.list}></PCChatTable>
                                                        </>
                                                    )}
                                                    {message.query_type === 'phone' && (
                                                        <>
                                                            <PhoneChatTable phones={message.list}></PhoneChatTable>
                                                        </>
                                                    )}
                                                </Table>
                                            ) : (
                                                <Text>{message.content}</Text>
                                            )
                                        ) : (
                                            <img
                                                src={message.content}
                                                alt="received"
                                                style={{
                                                    maxWidth: '100%',
                                                    borderRadius: '8px'
                                                }}
                                            />
                                        )}
                                    </Paper>
                                ))}
                                <div ref={scrollRef} />
                            </ScrollArea>
                        </Paper>

                        <form onSubmit={form.onSubmit(handleSubmit)} style={{ width: '100%', marginTop: '1rem' }}>
                            <Textarea
                                autosize
                                minRows={1}
                                maxRows={4}
                                maxLength={100}
                                placeholder="请输入你想问的内容"
                                onKeyDown={handleKeyDown}
                                styles={(theme) => ({
                                    input: {
                                        height: '80px',
                                        borderRadius: '20px',
                                        padding: '12px 16px',
                                        backgroundColor: '#fff',
                                        border: '1px solid #e5e5e5',
                                        boxShadow: '0 1px 3px rgba(0, 0, 0, 0.1)'
                                    },
                                    section: {
                                        width: '120px',
                                        right: '8px',
                                        display: 'flex',
                                        flexDirection: 'row',
                                        alignItems: 'center',
                                        justifyContent: 'space-between'
                                    }
                                })}
                                rightSection={
                                    <Group align="center" style={{ height: '100%' }} py={6}>
                                        <Button
                                            type="submit"
                                            variant="filled"
                                            size="xs"
                                            style={{ height: '100%' }}
                                        >
                                            发送
                                        </Button>
                                        <Text size="xs" color="dimmed">
                                            {form.values.message.length}/100
                                        </Text>
                                    </Group>
                                }
                                {...form.getInputProps('message')}
                            />
                        </form>
                    </Stack>
                );
            case 'phone':
                return (
                    <PhonePage></PhonePage>
                );
            case 'camera':
                return (
                    <CameraPage></CameraPage>
                );
            case 'earphone':
                return (
                    <EarphonePage></EarphonePage>
                );
            case 'logout':
                navigate('/login');
            default:
                return <div>Coming Soon...</div>;
        }
    };

    return (
        <AppShell
            padding="md"
            navbar={{
                width: 300,
                breakpoint: 'sm',
            }}
            header={{ height: 60 }}
        >
            <AppShell.Header p="md">
                <Group justify="space-between">
                    <Group>
                        <Avatar
                            // src={userInfo.avatar}
                            // alt={userInfo.username}
                            radius="xl"
                            size="md"
                        />
                        <div>
                            {/* <Text fw={500}>{userInfo.username}</Text> */}
                            <Text fw={500}>{JSON.parse(localStorage.getItem('user') as string).nickname}</Text>
                            {/* <Text size="xs" c="dimmed">上次登录: {userInfo.lastLogin}</Text> */}
                        </div>
                    </Group>
                </Group>
            </AppShell.Header>
            <AppShell.Navbar p="md" style={{ display: 'flex', flexDirection: 'column' }} styles={{

            }}>
                <AppShell.Section grow>
                    <Stack>
                        <NavLink
                            label="电脑信息"
                            active={active === 'home'}
                            onClick={() => setActive('home')}
                        />
                        <NavLink
                            label="手机信息"
                            active={active === 'phone'}
                            onClick={() => setActive('phone')}
                        />
                        <NavLink
                            label="相机信息"
                            active={active === 'camera'}
                            onClick={() => setActive('camera')}
                        />
                        <NavLink
                            label="耳机信息"
                            active={active === 'earphone'}
                            onClick={() => setActive('earphone')}
                        />
                        <NavLink
                            label="对话"
                            active={active === 'chat'}
                            onClick={() => setActive('chat')}
                        />
                    </Stack>
                </AppShell.Section>
                <AppShell.Section>
                    <Button
                        color="red"
                        variant="light"
                        onClick={() => setActive('logout')}
                        fullWidth
                        style={{ borderRadius: '8px' }}
                    >
                        退出登录
                    </Button>
                </AppShell.Section>
            </AppShell.Navbar>

            <AppShell.Main style={{ backgroundColor: '#f5f5f5' }}>
                <Modal
                    opened={modalOpened}
                    onClose={() => setModalOpened(false)}
                    title="详细信息"
                    size="lg"
                >
                    {selectedItem && (
                        <Stack>
                            {Object.entries(selectedItem).map(([key, value]) => (
                                <Group key={key}>
                                    <Text>{key}:</Text>
                                    <Text>{String(value)}</Text>
                                </Group>
                            ))}
                        </Stack>
                    )}
                </Modal>
                <div className={'mx-[unset]'} >
                    {renderContent()}
                </div>
            </AppShell.Main>
        </AppShell>
    );
}